<template>
	<view class="container">
		<view class="logo"><u-image width="300" height="300" :src="logo"></u-image></view>
		<view style="display: flex;justify-content: center;">登录成功，跳转中...</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			logo: '/static/qlzj.jpg',
			routePath: '',
			userInfo: {
				avatar:'',
				nickName:'',
				openid:'',
				sex:'',
				userId:''
			}
		};
	},
	methods: {
		isWechat() {
			return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === 'micromessenger';
		},
		getWxCode() {
			if (this.isWechat()) {
				// 截取地址中的code，如果没有code就去微信授权，如果已经获取到code了就直接把code传给后台获取openId
				window.location.href =
					'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe283a89e01985b0d' +
					'&redirect_uri=' +
					encodeURIComponent('http://www.mksoft.cn/qlyg/#/pages/wxlogin/jump') +
					'&response_type=code&scope=snsapi_userinfo&state=' + encodeURIComponent(this.routePath)
					+'#wechat_redirect';
				// redirect_uri是授权成功后，跳转的url地址，微信会帮我们跳转到该链接，并且通过？的形式拼接code，这里需要用encodeURIComponent对链接进行处理。
				// 如果配置参数一一对应，那么此时已经通过回调地址刷新页面后，你就会再地址栏中看到code了。
				// http://127.0.0.1/pages/views/profile/login/login?code=001BWV4J1lRzz00H4J1J1vRE4J1BWV4q&state=1
			}
		},
		getUrlCode(name) {
			return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null;
		},
		getOpenidAndUserinfo(code) {
			uni.request({
				url: 'http://www.mksoft.cn/zx/front/wx/wxlogin',
				data: {
					code: code
				},
				success: res => {
					if (res.data.code == 200) {
						// 登录成功（第一次登录将默认注册）
						this.userInfo.avatar = res.data.data.avatar;
						this.userInfo.nickName = res.data.data.nickName;
						this.userInfo.openid = res.data.data.wxOpenId;
						this.userInfo.sex = res.data.data.sex;
						this.userInfo.userId = res.data.data.userId;
						uni.setStorageSync('h5_wx_code', code);
						uni.setStorageSync("h5_wx_user",res.data.data);
						//alert(this.routePath)
						window.location.href = 'http://www.mksoft.cn/qlyg/#'+ this.routePath;
						//this.$Router.push(this.routePath);
					} else if (res.data.data.code == 400) {
						// token已过期，需要重新授权
						this.getWxCode();
					}
				},
				fail: res => {
					uni.showToast({
						title: '获取用户信息失败',
						icon: 'none',
						duration: 2500
					});
				}
			});
		}
	},
	onLoad() {
		// 获取跳转地址
		let state = this.getUrlCode('state');
		if (state) {
			this.routePath = decodeURIComponent(state);
		}
		if (this.routerPath == '/pages/wxlogin/wxlogin' || !this.routerPath) {
			this.routerPath = '/pages/index/index';
		}
		// 获取微信用户信息
		let code = this.getUrlCode('code');
		if (code) {
			this.getOpenidAndUserinfo(code);
		}
	}
};
</script>

<style>
.logo {
	display: flex;
	justify-content: center;
}
</style>
